package com.cloud.workTest;

import com.aliyun.odps.Column;
import com.aliyun.odps.Odps;
import com.aliyun.odps.Partition;
import com.aliyun.odps.Table;
import com.aliyun.odps.account.Account;
import com.aliyun.odps.account.AliyunAccount;

import java.util.ArrayList;
import java.util.List;

public class ReadAllPartitions {

    public static void main(String[] args) {
        Account account = new AliyunAccount("LTAI5tFKQUiDtZrrioE85MUT", "jNSQevwtROFzg6dYX3XTg4EeftsiSY");
        Odps odps = new Odps(account);
        String odpsUrl = "https://service.cn-hangzhou.maxcompute.aliyun.com/api";
        String tableName = "test_shucb";
        odps.setEndpoint(odpsUrl);
        odps.setDefaultProject("df_ch_100935");

        Table table = odps.tables().get(tableName);

        System.out.println(table.getFileNum());

        if (table.getSchema().getPartitionColumns().size() == 0) {
            System.out.println("Table is not partitioned.");
            return;
        }
        // 列出所有分区
        List<Partition> partitions = new ArrayList<>();

        table.getPartitions().forEach(partition -> {System.out.println(partition.getPartitionSpec());});
        table.getPartitions().forEach(partitions::add);

        // 动态生成查询语句
        List<String> queryParts = new ArrayList<>();
        for (Partition partition : partitions) {
            StringBuilder partitionStr = new StringBuilder();
            for (Column column : table.getSchema().getPartitionColumns()) {
                if (partitionStr.length() > 0) {
                    partitionStr.append(" AND ");
                }
                partitionStr.append(column.getName()).append("='").append(partition.getPartitionSpec().get(column.getName())).append("'");
            }
            queryParts.add(String.format("SELECT * FROM %s WHERE %s", tableName, partitionStr.toString()));
        }
        String fullQuery = String.join(" UNION ALL ", queryParts);

        System.out.println(fullQuery);
    }
}
